package com.ellfors.common.base

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.core.view.isVisible
import com.ellfors.common.R
import com.ellfors.common.databinding.IncludeBaseTitleBarBinding
import com.ellfors.common.ext.dp2px

class BaseTitleBar : FrameLayout {

    private var mBinding: IncludeBaseTitleBarBinding? = null
    private var mBackClickListener: (() -> Unit)? = null

    companion object {
        val TITLE_BAR_HEIGHT = 45.dp2px()
    }

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init()
    }

    private fun init() {
        LayoutInflater.from(context).inflate(R.layout.include_base_title_bar, this)
        mBinding = IncludeBaseTitleBarBinding.bind(rootView)
        mBinding?.ivBack?.setOnClickListener {
            mBackClickListener?.invoke() ?: also {
                if (context is Activity) {
                    (context as Activity).finish()
                }
            }
        }
    }

    fun setTitle(title: String) {
        mBinding?.tvTitle?.text = title
    }

    fun switchCloseVisible(flag: Boolean) {
        mBinding?.ivBack?.isVisible = flag
    }

    fun setOnBackClickListener(listener: (() -> Unit)?) {
        this.mBackClickListener = listener
    }
}